package cn.shujuhai.workflow.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import cn.shujuhai.common.aop.SysLogAspect;
import cn.shujuhai.common.pluging.data.ResultVo;
import cn.shujuhai.common.pluging.file.FilesUtils;
import cn.shujuhai.workflow.domain.Form;
import cn.shujuhai.workflow.domain.FormData;
import cn.shujuhai.workflow.mapper.FormDataMapper;
import cn.shujuhai.workflow.service.FormDataService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.yulichang.wrapper.JoinAbstractLambdaWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.el.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhangDeZhong
 * @description 针对表【form_data】的数据库操作Service实现
 * @createDate 2025-03-11 09:40:20
 */
@Service
public class FormDataServiceImpl extends ServiceImpl<FormDataMapper, FormData>
        implements FormDataService {

    @Value("${template.static.workflow.formImgUrl}")
    public String UPLOAD_IMG_DIR;        //图片上传路径

    @Value("${template.static.workflow.formFileUrl}")
    public String UPLOAD_FILE_DIR;        //文件上传路径

    @Value("${template.static.workflow.viewFormImgUrl}")
    public String VIEW_IMG_DIR;        //图片访问路径

    @Value("${template.static.workflow.viewFormFileUrl}")
    public String VIEW_FILE_DIR;        //文件访问路径

    private static final Logger logger = LoggerFactory.getLogger(SysLogAspect.class);


    @Override
    public ResultVo<?> getFormDataList(Long formId, Object formData, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<FormData> formDataList = this.list(Wrappers.<FormData>lambdaQuery()
                .eq(FormData::getFormId, formId)
                .like(FormData::getFormData, formData)
                .orderByDesc(FormData::getFormDataId));
        PageInfo<FormData> pageInfo = new PageInfo<>(formDataList);
        return ResultVo.success(pageInfo);
    }

    @Override
    public ResultVo<?> addFormData(FormData formData) {
        String submitUser = "匿名用户";
        try {
            if (StpUtil.isLogin()) {
                submitUser = StpUtil.getSession().get("username").toString();
            }
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
        formData.setSubmitUser(submitUser);
        boolean save = this.save(formData);
        if (save) {
            return ResultVo.success();
        }
        return ResultVo.failure("表单数据提交失败");
    }


    @Override
    public ResultVo<?> deleteFormData(Long formDataId) {
        boolean remove = this.removeById(formDataId);
        if (remove) {
            return ResultVo.success();
        }
        return ResultVo.failure("表单数据删除失败");
    }

    @Override
    public ResultVo<?> removeBatchFormData(List<Long> formDataIds) {
        boolean removeByIds = this.removeByIds(formDataIds);
        if (removeByIds) {
            return ResultVo.success();
        }
        return ResultVo.failure("表单数据删除失败");
    }


    @Override
    public ResultVo<?> uploadImg(MultipartFile file, Long formId) {
        try {
            // 校验文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null || !fileName.matches("^(?i).*(\\.jpg|\\.png|\\.webp)$")) {
                return ResultVo.failure("仅支持上传webp、jpg 和 png 格式的图片");
            }
            // 校验文件大小
            long maxSize = 500 * 1024;
            if (file.getSize() > maxSize) {
                return ResultVo.failure("图片大小不能超过 500KB");
            }
            String uploadedFile = FilesUtils.uploadFormFile(file, UPLOAD_IMG_DIR, VIEW_IMG_DIR, formId);
            return ResultVo.success(uploadedFile);
        } catch (RuntimeException e) {
            return ResultVo.failure(e.getMessage());
        }
    }

    @Override
    public ResultVo<?> uploadFile(MultipartFile file, Long formId) {
        try {
            // 校验文件类型，支持的文件格式
            String fileName = file.getOriginalFilename();
            if (fileName == null || !fileName.matches("^(?i).*(\\.zip|\\.rar|\\.pdf|\\.xlsx)$")) {
                return ResultVo.failure("仅支持上传的文件格式为zip,rar,pdf,xlsx");
            }
            // 校验文件大小
            long maxSize = 200 * 1024;
            if (file.getSize() > maxSize) {
                return ResultVo.failure("文件大小不能超过 20MB");
            }
            String uploadedFile = FilesUtils.uploadFormFile(file, UPLOAD_FILE_DIR, VIEW_FILE_DIR, formId);
            return ResultVo.success(uploadedFile);
        } catch (RuntimeException e) {
            return ResultVo.failure(e.getMessage());
        }
    }

    @Override
    public ResultVo<?> uploadIceImg(MultipartFile[] files, Long formId) {
        try {
            List<String> uploadedFiles = new ArrayList<>();
            for (MultipartFile file : files) {
                // 校验文件类型
                String fileName = file.getOriginalFilename();
                if (fileName == null || !fileName.matches("^(?i).*(\\.jpg|\\.png|\\.webp)$")) {
                    return ResultVo.failure("仅支持上传 webp、jpg 和 png 格式的图片");
                }
                // 校验文件大小
                long maxSize = 500 * 1024;
                if (file.getSize() > maxSize) {
                    return ResultVo.failure("图片大小不能超过 500KB");
                }
                // 上传文件并获取上传后的路径
                String uploadedFile = FilesUtils.uploadFormFile(file, UPLOAD_IMG_DIR, VIEW_IMG_DIR, formId);
                uploadedFiles.add(uploadedFile);
            }
            // 返回所有成功上传的文件路径
            return ResultVo.success(uploadedFiles);
        } catch (RuntimeException e) {
            return ResultVo.failure(e.getMessage());
        }
    }


}




